package pit.com.ordermobilesystem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pit.com.ordermobilesystem.adapter.OrderItemAdapter;
import pit.com.ordermobilesystem.constant.OrderConstant;
import pit.com.ordermobilesystem.fragment.HomeFragment;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider.ItemTable;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import pit.com.ordermobilesystem.widget.CustomProgressDialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

public class ShopActivity extends ActionBarActivity implements BaseFragmentInterface ,OrderConstant {
    CustomProgressDialog progressDialog;
    HomeFragment mFrag;

    OrderItemAdapter orderItemAdapter;

    ListView lv_order;
    ScrollView mDrawerList;
    
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    JSONObject data;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     try {
		 data=new JSONObject(getIntent().getStringExtra("data"));
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}   

	TextView tv_payment=(TextView) findViewById(R.id.tv_payment_menu);
	tv_payment.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			TextView tv_total_invoice=(TextView) findViewById(R.id.tv_total_invoice);
			Intent intent=new Intent(ShopActivity.this,InvoiceActivity.class);
			intent.putExtra("total", tv_total_invoice.getText());
			startActivity(intent);
			
		}
	});
	
	
        mTitle = mDrawerTitle = getTitle();
        lv_order=(ListView) findViewById(R.id.lv_order);
        mDrawerList=(ScrollView) findViewById(R.id.menu_frame);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_head_back, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);	
        
	if(mFrag == null){
		mFrag=new HomeFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();   
		 transaction.replace(R.id.content_frame, mFrag, HomeFragment.class.getName());
		 transaction.addToBackStack(HomeFragment.class.getName());

	    transaction.commit();
	}		

        getActionBar().setDisplayHomeAsUpEnabled(true);

    }

    public void openDrawer(){
	    	if(mDrawerLayout.isDrawerOpen(mDrawerList)){
				mDrawerLayout.closeDrawer(mDrawerList);
			}else{
				mDrawerLayout.openDrawer(mDrawerList);
			}
    }
    

    
    public JSONObject getData() {
		return data;
	}

	public void setData(JSONObject data) {
		this.data = data;
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

	/**
	 * @author NMTHONG
	 * @since 17/5/2013
	 * @param title
	 * @param message
	 * @param onCancel
	 */
	public void showProgressDialog(DialogInterface.OnCancelListener onCancel) {
		if (progressDialog == null) {
			progressDialog = new CustomProgressDialog(this);
			progressDialog.setOnCancelListener(onCancel);
		}
		progressDialog.show();

	}

	/**
	 * @author NMTHONG
	 * @since 17/5/2013
	 */
	public void hideProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}

	}

	/**
	 * @author NMTHONG
	 * @since 17/5/2013
	 * @param title
	 * @param message
	 */
	public void showAlert(String title, String message) {
		new AlertDialog.Builder(this).setTitle(title).setMessage(message).setPositiveButton(R.string.ok, null).show();
	} 
	
	

	
	


	    @Override
	    public void onBackPressed() {
		    boolean isPopFragment = false;
		    isPopFragment = mFrag.popFragment();

		    if (!isPopFragment) {
		        finish();
		    }
	    }
	    
	    
	    
	    
		ContentObserver contentObserver = new ContentObserver(new Handler()) {

			@Override
			public void onChange(boolean selfChange) {
				super.onChange(selfChange);
				synchronized (this) {
					JSONObject shop;
					try {
						shop = new JSONObject(OrderSharePreference.getShop(getApplicationContext()));
						Cursor data = getContentResolver().query(
								OrderMobileProvider.ITEM_CONTENT_URI, null, ItemTable.NUMBER_ORDER+">0 AND "+ItemTable.SALE_ID+"="+shop.getInt("id"), null,
								null);
						if (data != null) {
				
								if (orderItemAdapter == null) {
									orderItemAdapter = new OrderItemAdapter(ShopActivity.this, data);
									lv_order.setAdapter(orderItemAdapter);
								} else {
	
									orderItemAdapter.changeCursor(data);
									
								}	
								calculateTotalPrice();
	
						}	
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		};	
		@Override
		public void onPause() {
			super.onPause();
			getContentResolver().unregisterContentObserver(contentObserver);		
		}

		@Override
		public void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			contentObserver.onChange(true);
			getContentResolver().registerContentObserver(OrderMobileProvider.ITEM_CONTENT_URI, true, contentObserver);
		}

		@Override
		protected void onDestroy() {
			if(orderItemAdapter!=null){
				orderItemAdapter.changeCursor(null);
			}
			OrderSharePreference.setShop(this,"");
			//Delete all items order
			getContentResolver().delete(OrderMobileProvider.ITEM_CONTENT_URI, null, null);
			super.onDestroy();
		}
		
		public void calculateTotalPrice(){
			
				String nameColumn="SUM("+ItemTable.PRICE+"*"+ItemTable.NUMBER_ORDER+") AS TOTAL";
				String[] column={nameColumn};
				JSONObject shop;

				try {
						shop = new JSONObject(OrderSharePreference.getShop(getApplicationContext()));
						Cursor data = getContentResolver().query(OrderMobileProvider.ITEM_CONTENT_URI, column, ItemTable.NUMBER_ORDER+">0 AND "+ItemTable.SALE_ID+"="+shop.getInt("id"), null,null);
						if (data != null) {
							if(data.moveToNext()){
								TextView tv_total_invoice=(TextView) findViewById(R.id.tv_total_invoice);
								TextView tv_total_invoice_right_menu=(TextView) mDrawerList.findViewById(R.id.tv_total_invoice);
								tv_total_invoice.setText(data.getString(data.getColumnIndex("TOTAL")));
								tv_total_invoice_right_menu.setText(data.getString(data.getColumnIndex("TOTAL")));
							}
							data.close();
						}							
				} catch (JSONException e) {
						e.printStackTrace();
				}
				
		}	
		

		public void setTitleActionBar(String title){

		}

		public void setTitleActionBar(int title){

		}
		
		    @Override
		    protected void onPostCreate(Bundle savedInstanceState) {
		        super.onPostCreate(savedInstanceState);
		        // Sync the toggle state after onRestoreInstanceState has occurred.
		        mDrawerToggle.syncState();
		    }

		    @Override
		    public void onConfigurationChanged(Configuration newConfig) {
		        super.onConfigurationChanged(newConfig);
		        mDrawerToggle.onConfigurationChanged(newConfig);
		    }

		    @Override
		    public boolean onOptionsItemSelected(MenuItem item) {
			int id = item.getItemId();
		        // Handle your other action bar items...
			if(id==android.R.id.home){
				onBackPressed();

			}else if(id==R.id.mn_cart){
				openDrawer();
			}
		        return super.onOptionsItemSelected(item);
		    }		
		    
		    public void addFragment(BaseFragment frag){
			    mFrag.addFragment(frag);
		    }
		    
		    public void popFragment(){
			    mFrag.popFragment();
		    }

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			mFrag.onActivityResult(requestCode, resultCode, data);
			super.onActivityResult(requestCode, resultCode, data);
		}


		    
		    
		    
}
